var express = require('express')
var router = express.Router()
const { getAll, getOne, exec } = require('../../db/index')

// 获取点击量最高的四篇文章
router.get('/article', async (req, res) => {
  let sql = `select id,author,title,imgPath,click from blog_articles order by click Desc limit 0,4 `
  const data = await getAll(sql)
  res.send({
    code: 0,
    message: '查询成功',
    result: data,
  })
})
// 获取单个文章的评论
router.get('/comment/:id', async (req, res) => {
  const { id } = req.params
  let sql = `select * from blog_comment where article_id = ${id}`
  const data = await getAll(sql)
  res.send({
    code: 0,
    message: '查询成功',
    result: data,
  })
})
// 获取文章数量最多的四个分类类名
router.get('/type', async (req, res) => {
  let sql = `select * from blog_category`
  const data = await getAll(sql)
  res.send({
    code: 0,
    message: '查询成功',
    result: data,
  })
})
// 根据关键字搜索文章类型
router.post('/typekeyword', async (req, res) => {
  const { keyword } = req.body
  let sql = `select * from blog_category where type like '%${keyword}%'`
  const data = await getAll(sql)
  res.send({
    code: 0,
    message: '查询成功',
    result: data,
  })
})
// 获取所有的文章
router.get('/allArticle', async (req, res) => {
  let sql = `select * from blog_articles`
  const data = await getAll(sql)
  res.send({
    code: 0,
    message: '查询成功',
    result: data,
  })
})
// 增加点击量
router.put('/click/:id', async (req, res) => {
  const { id } = req.params
  let sql = `update blog_articles set click=click+1 where id=${id};`
  await exec(sql)
  res.send({
    code: 0,
    message: '新增点击量成功',
  })
})
// 根据id查询文章
router.get('/oneArticle/:id', async (req, res) => {
  const { id } = req.params
  let sql = `select * from blog_articles where id =${id}`
  const data = await getOne(sql)
  res.send({
    code: 0,
    message: '查询成功',
    result: data,
  })
})
// 在对应id添加评论
router.post('/addcomment/:id', async (req, res) => {
  const { id } = req.params
  const { keyword } = req.body
  let sql = `insert into blog_comment (content,article_id) values('${keyword}',${id})`
  await exec(sql)
  res.send({
    code: 0,
    message: '评论成功',
  })
})

module.exports = router
